package com.fs.groupSeven.realm;


import com.fs.groupSeven.pojo.Permission;
import com.fs.groupSeven.pojo.Role;
import com.fs.groupSeven.pojo.User;
import com.fs.groupSeven.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.HashSet;
import java.util.Set;

/**
 * @description:
 * @author： mjx
 * @createDate: 2020/9/25
 * @version: 1.0
 */

public class MyShiroRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = (String) authenticationToken.getPrincipal();
        User user = userService.getOneByUsername(username);
        if (user == null) {
            throw new UnknownAccountException(username + "，查无此人");//抛出异常表明没有这个用户
        }

        Session session = SecurityUtils.getSubject().getSession();
        session.setAttribute("user", user);
        String password = user.getPassword();
        String realName = this.getName();
        ByteSource byteSource = ByteSource.Util.bytes(user.getUsername());
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username, password, byteSource, realName);
        return info;
    }

    //传入的参数就是待授权的用户
    //告诉shiro系统，某个用户对应的权限相关信息（授权）
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //拿到待授权的用户信息
        String username = (String) principalCollection.getPrimaryPrincipal();
        //根据要认证的用户账号去系统里面查询相关信息
        User user = userService.getOneByUsername(username);
        Set<String> roles = new HashSet<>();
        //收集user的角色信息
        for (Role role : user.getRoles()) {
            roles.add(role.getName());
        }
        //创建一个授权信息对象，依此来收集用户的角色信息和权限信息
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRoles(roles);
        return info;
    }
}
